package controlleur.form;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import annuaire.beans.Promotion;
import annuaire.beans.Student;
import annuaire.exceptions.BusinessException;
import annuaire.rmi.remotedObject.IRemotedAnnuaire;
import annuaire.rmi.remotedObject.IRemotedUser;
import form.bean.StudentForm;

/**
 * Controlleur responsable de la mise a jour d'un etudiant
 * 
 * @author Yannick Lorenzati & Stephanie Malakian
 * 
 */
public class UpdateStudentFormControlleur extends SimpleFormController {

	/** Logger pour cette classe ainsi que pour ses sous classes */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * Reference vers l'objet distant Annuaire
	 */
	private IRemotedAnnuaire remotedAnnuaire;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object commandAjout,
			BindException errors) throws Exception {

		logger.info("on arrive dans onubmit********************************");

		IRemotedUser user = (IRemotedUser) request.getSession().getAttribute(
				"user");
		StudentForm s = (StudentForm) commandAjout;

		// On check le nouveux login soit pas deja pris
		Student oldStudent = remotedAnnuaire.findStudentById(Integer
				.parseInt(request.getParameter("id")));

		// si le login a changé
		if (!oldStudent.getLogin().equals(s.getLogin())) {

			Student pattern = new Student();
			pattern.setLogin(s.getLogin());
			pattern = remotedAnnuaire.searchOneStudent(pattern);

			// si nouveau login deja pris
			if (pattern != null) {
				errors.rejectValue("login", "key", "Ce login est deja pris");
				return showForm(request, response, errors);
			}
		}

		// on update
		Student newStudent = oldStudent;
		newStudent.setAddress(s.getAddress());
		newStudent.setComments(s.getComments());
		newStudent.setFirstName(s.getFirstName());
		newStudent.setName(s.getName());
		newStudent.setLogin(s.getLogin());
		newStudent.setMail(s.getMail());
		newStudent.setWeb(s.getWeb());
		newStudent.setSociety(s.getSociety());

		if (s.getIdPromo() == null || s.getIdPromo().isEmpty()) {
			newStudent.setPromo(null);
		} else {
			int idp = Integer.parseInt(s.getIdPromo());
			newStudent.setPromo(remotedAnnuaire.findPromoById(idp, false));
		}

		user.getStudentService().updateStudent(newStudent);

		//		
		// if(!s.getIdPromo().equals("") && s.getIdPromo() != null){
		// int idp = Integer.parseInt(s.getIdPromo());
		// Set<Student> set = new HashSet<Student>();
		// set.add(newStudent);
		// user.getAdminService().addStudentsToPromo(remotedAnnuaire.findPromoById(idp,
		// false),set);
		// }

		ModelAndView mav = showNewForm(request, response);
		mav.addObject("succesStu", "Etudiant modifié avec succes");
		return mav;
		// return new ModelAndView(getSuccessView(), "model", myModel);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.web.servlet.mvc.AbstractFormController#
	 * handleRequestInternal(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String errorGet = null;

		// si id n'est pas fourni
		String idStu = request.getParameter("id");
		if (idStu == null || idStu.equals("")) {
			errorGet = "erreur id abscent";
		} else {
			// si l'id n'est pas un nombre
			try {

				int id = Integer.parseInt(idStu);

				// si l'id n'existe pas
				Student s = remotedAnnuaire.findStudentById(id);
				if (s == null) {
					errorGet = "erreur id inexistant";
				}

			} catch (NumberFormatException e) {
				errorGet = "l'id n'est pas un entier valide";
			}
		}

		if (errorGet != null) {
			logger.info("un petit malin a tenté de jouer avec l'url");
			// ModelAndView mav = showForm(request, response,null);
			ModelAndView mav = new ModelAndView(getFormView());
			mav.addObject("errorGet", errorGet);
			return mav;
		} else {
			logger.info("pas d'eurreur d'url");
			return super.handleRequestInternal(request, response);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject
	 * (javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws ServletException {

		StudentForm studentForm = new StudentForm();
		Student s;
		try {
			s = remotedAnnuaire.findStudentById(Integer.parseInt(request
					.getParameter("id")));

			studentForm.setAddress(s.getAddress());
			studentForm.setPwd(s.getPwd());
			studentForm.setComments(s.getComments());
			studentForm.setFirstName(s.getFirstName());
			studentForm.setLogin(s.getLogin());
			studentForm.setMail(s.getMail());
			studentForm.setName(s.getName());
			studentForm.setSociety(s.getSociety());
			studentForm.setWeb(s.getWeb());

			if (s.getPromo() == null) {
				studentForm.setIdPromo(null);
			} else {

				studentForm.setIdPromo(Integer.toString(s.getPromo().getId()));
			}

		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		}

		return studentForm;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#referenceData
	 * (javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Map<String, Object> referenceData(HttpServletRequest request)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();

		Collection<Integer> listIdPromo = remotedAnnuaire.findAllPromosId();
		List<Promotion> listPromo = new ArrayList<Promotion>();

		for (Integer id : listIdPromo) {
			Promotion p = remotedAnnuaire.findPromoById(id, false);
			StringBuilder newTitle = new StringBuilder();
			newTitle.append(p.getPromoYear());
			newTitle.append(" : ");
			newTitle.append(p.getTitle());
			p.setTitle(newTitle.toString());
			listPromo.add(p);

		}

		map.put("listPromo", listPromo);

		return map;

	}

	/**
	 * @param remotedAnnuaire
	 */
	public void setRemotedAnnuaire(IRemotedAnnuaire remotedAnnuaire) {
		this.remotedAnnuaire = remotedAnnuaire;
	}

	/**
	 * @return
	 */
	public IRemotedAnnuaire getRemotedAnnuaire() {
		return remotedAnnuaire;
	}

}
